import { debounce } from 'lodash';
import { onBeforeUnmount, onMounted, ref } from 'vue';

type ContextId = '2d';
// todo 优化事件监听，实现某一个功能就监听某一种行为的功能，而不是重复的监听
export const useCanvas = (context: ContextId = '2d') => {
    const canvasDom = ref<HTMLCanvasElement>(), offCanvasDom = ref<HTMLCanvasElement>();
    let ctx: CanvasRenderingContext2D | null | undefined;
    let isDraw = false;
    const onMousedown = function (e: MouseEvent) {
        console.log(111, e)
        if (canvasDom.value) {
            canvasDom.value.addEventListener('mouseup', onMouseup)
            canvasDom.value.addEventListener('mousemove', onMousemove)
            canvasDom.value.addEventListener('mouseleave', onMouseleave)
            isDraw = true;
            ctx?.beginPath();
            ctx?.moveTo(e.offsetX, e.offsetY)
        }
    }
    const onMouseup = function (e: MouseEvent) {
        if (canvasDom.value) {
            isDraw = false
            ctx?.closePath();
            canvasDom.value.removeEventListener('mouseup', onMouseup)
            canvasDom.value.removeEventListener('mousemove', onMousemove)
            canvasDom.value.removeEventListener('mouseleave', onMouseleave)
        }
    }
    const onMouseleave = function (e: MouseEvent) {
        if (canvasDom.value) {
            isDraw = false
            ctx?.closePath();
            canvasDom.value.removeEventListener('mouseup', onMouseup)
            canvasDom.value.removeEventListener('mousemove', onMousemove)
            canvasDom.value.removeEventListener('mouseleave', onMouseleave)
        }
    }
    const onMousemove = function (e: MouseEvent) {
        if (isDraw) {
            ctx?.lineTo(e.offsetX, e.offsetY)
            ctx?.stroke();
        }
    }
    const useDrawingBoard = () => {
        if (canvasDom.value && ctx !== null && ctx !== undefined) {
            canvasDom.value.addEventListener('mousedown', onMousedown)
        }
    }

    const setLineWidth = (width: number) => {
        if (ctx) {
            ctx.lineWidth = width;
        }
    }

    const clear = () => {
        if (ctx) {
            ctx.clearRect(0, 0, canvasDom.value?.width || 0, canvasDom.value?.height || 0);
        }
    }

    const saveImg = () => {
        if (canvasDom.value) {
            const url = canvasDom.value.toDataURL();

            const a = document.createElement('a');
            a.setAttribute('download', '签名');
            a.href = url;
            a.click();
            setTimeout(() => {
              document.body.removeChild(a);
            }, 100);
        }
    }

    const setStrokeStyle = (style: string) => {
        if (ctx) {
            ctx.strokeStyle = style;
        }
    }

    const isGrab = ref(false);
    const useGrab = () => {
        if (ctx) {
            if (canvasDom.value) {
                canvasDom.value.addEventListener('mousedown', () => {
                    if (ctx) {
                        isGrab.value = true;
                        ctx.save();
                        ctx.globalCompositeOperation = 'destination-out'
                        setLineWidth(30);
                    }
                }, { once: true })

                canvasDom.value.addEventListener('mouseup', () => {
                    if (ctx) {
                        isGrab.value = false;
                        ctx.restore();
                    }
                }, { once: true })
            }
        }

    }

    const debounceResize = debounce(() => {
        if (canvasDom.value) {
            canvasDom.value.width = canvasDom.value.offsetWidth;
            canvasDom.value.height = canvasDom.value.offsetHeight;
        }
    }, 300)

    onMounted(() => {
        if (canvasDom.value) {
            ctx = canvasDom.value.getContext(context);
            console.log(11111111, canvasDom)
            canvasDom.value.width = canvasDom.value.offsetWidth;
            canvasDom.value.height = canvasDom.value.offsetHeight;
            if (ctx) {
                ctx.lineCap = 'round';
                ctx.lineJoin = 'round';
            }
            useDrawingBoard();
            if (offCanvasDom.value) {
                offCanvasDom.value.width = canvasDom.value.width * 2;
                offCanvasDom.value.height = canvasDom.value.height * 2;
            }
            // todo 尺寸变化时，需要重新绘制，可以使用离屏canvas进行缓存
            // window.addEventListener('resize', debounceResize)
        }
    })
    onBeforeUnmount(() => {
        // window.removeEventListener('resize', debounceResize);
        canvasDom.value?.removeEventListener('mouseup', onMouseup)
    })

    return { canvasDom, offCanvasDom, setLineWidth, useGrab, isGrab, setStrokeStyle, clear, saveImg }
}